package im.starchat.chat.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.toolbox.StringRequest;
import com.tencent.av.sdk.AVError;
import com.tencent.av.sdk.AVRoom;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.adapter.LiveAdapter;
import im.starchat.chat.control.QavsdkControl;
import im.starchat.chat.dialog.ShareRoomDialogFragment;
import im.starchat.chat.rest.RestClient;
import im.starchat.chat.rest.model.RoomBean;
import im.starchat.chat.utils.Constants;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.RetrofitErrorUtil;
import im.starchat.chat.utils.Util;
import im.starchat.chat.view.swipeRefreshLayout.SwipeRefreshLayout;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by liuchao on 2/3/16.
 * 直播 fragment
 */
public class LiveFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener{

    private static final String TAG = "LiveFragment";

    @InjectView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @InjectView(R.id.swipe_refresh_layout_list)
    SwipeRefreshLayout mSwipeRefreshLayout;

    private QavsdkControl mQavsdkControl;
    private LiveAdapter mLiveAdapter;
    private LinearLayoutManager mLayoutManager;
    private int mCurrentPage = RestClient.DEFAULT_PAGE;
    private boolean mHasMoreData = true;
    //type: 关注 following 热门 hot 最新 newest
    private static final String TYPE = "type";

    public LiveFragment() {
    }

    public static LiveFragment newInstance(String type) {
        LiveFragment fragment = new LiveFragment();
        Bundle bundle = new Bundle();
        bundle.putString( TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
////        broadcastManager.unregisterReceiver(mBroadcastReceiver);
//    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_live, container, false);
        ButterKnife.inject(this, view);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);

        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mLiveAdapter = new LiveAdapter(getActivity(), new LiveAdapter.LiveAdapterCallback() {
            @Override
            public void onItemClick(RoomBean feedBean) {
//                if (feedBean != null && feedBean.getUser().getId() == (UserUtils.getUserInstance().getId())) {
//                    Toast.makeText(getActivity(), "你不能加入自己的房间", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                Log.d(TAG, "onItemClick isCreater false"+feedBean);
                Constants.setChooseRoomInfo(feedBean);
                createRoom(feedBean.getId(), AVRoom.AUTH_BITS_JOIN_ROOM|AVRoom.AUTH_BITS_RECV_AUDIO|AVRoom.AUTH_BITS_RECV_CAMERA_VIDEO|AVRoom.AUTH_BITS_RECV_SCREEN_VIDEO);
            }

            @Override
            public void onShareBtnClick(RoomBean roomBean) {
                final ShareRoomDialogFragment shareRoomDialogFragment = ShareRoomDialogFragment.newInstance(roomBean);
                shareRoomDialogFragment.show(getChildFragmentManager().beginTransaction(), "share_app");
            }
        });
        mRecyclerView.setAdapter(mLiveAdapter);
        mQavsdkControl = XLApplication.getQavsdkControl();

        getFeedList();

//        getLiveVideoInfo();

        return view;
    }

    @Override
    public void onRefresh() {
        mCurrentPage = RestClient.DEFAULT_PAGE;
        getFeedList();
    }

    @Override
    public void onLoad() {
        if(mHasMoreData){
            mCurrentPage ++;
            getFeedList();
        }else{
            mSwipeRefreshLayout.setRefreshing(false);
            mSwipeRefreshLayout.setLoading(false);
            Toast.makeText(getActivity(), "没有更多数据", Toast.LENGTH_SHORT).show();
        }

    }

//    private boolean isFirst = true;
//    private LiveVideoInfo mChoseLiveVideoInfo = null;
//    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            Log.d(TAG, "onReceive Broadcast");
//            String action = intent.getAction();
//            if (mSelfUserInfo.isCreater() == false) {
//                if (action.equals(Util.ACTION_ROOM_CREATE_COMPLETE)) {
//                    Log.d(TAG, "liveAcitivity onReceive ACTION_ROOM_CREATE_COMPLETE");
//                    int mCreateRoomErrorCode = intent.getIntExtra(
//                            Util.EXTRA_AV_ERROR_RESULT, AVError.AV_OK);
//                    if (isFirst) {
//                        try {
//                            Thread.sleep(1000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        isFirst = false;
//                    }
//
//                    if (mCreateRoomErrorCode == AVError.AV_OK) {
//                        if (mChoseLiveVideoInfo == null) {
////                            Toast.makeText(LiveActivity.this, "mChoseLiveVideoInfo is null !!!! ", Toast.LENGTH_SHORT).show();
//                            Log.e(TAG, "LiveActivity onReceive mChoseLiveVideoInfo is " + mChoseLiveVideoInfo);
//                            return;
//                        }
//                        startActivity(new Intent(getActivity(), AvActivity.class)
//                                .putExtra(Util.EXTRA_ROOM_NUM, mChoseLiveVideoInfo.getProgrammId()) //room id
//                                .putExtra(Util.EXTRA_SELF_IDENTIFIER, mChoseLiveVideoInfo.getUserPhone())
//                                .putExtra(Util.EXTRA_GROUP_ID, mChoseLiveVideoInfo.getLiveGroupId()) // chat converse id
//                                .putExtra(Util.EXTRA_PRAISE_NUM, mChoseLiveVideoInfo.getLivePraiseCount()));
//                        enterRoom();
//                    }
//                } else if (action.equals(Util.ACTION_CLOSE_ROOM_COMPLETE)) {
//
//                }
//                Log.d(TAG, "WL_DEBUG ANR  onReceive action = " + action + " Out");
//            }
//        }
//    };

    private void getFeedList(){
        XLApplication.getInstance().getRestClient().getFeedList(getArguments().getString(TYPE), mCurrentPage, RestClient.DEFAULT_PREPAGE, new Callback<List<RoomBean>>() {
            @Override
            public void success(List<RoomBean> feedBeans, Response response) {
                if(mCurrentPage == RestClient.DEFAULT_PAGE){
                    mLiveAdapter.refreshData(feedBeans);
                }else{
                    mLiveAdapter.addAll(feedBeans);
                }
                if(feedBeans.size()< 20){
                    mHasMoreData = false;
                }else{
                    mHasMoreData = true;
                }
                mSwipeRefreshLayout.setRefreshing(false);
                mSwipeRefreshLayout.setLoading(false);
            }

            @Override
            public void failure(RetrofitError error) {
                RetrofitErrorUtil.handleError(getActivity(), error);
                mSwipeRefreshLayout.setRefreshing(false);
                mSwipeRefreshLayout.setLoading(false);
            }
        });
    }

    private void createRoom(int num) {
        if (Util.isNetworkAvailable(getActivity().getApplicationContext())) {
            if (num != 0) {
                int nums = num;
                mQavsdkControl.enterRoom(nums);
                Toast.makeText(getActivity(), "正在进入直播中...", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getActivity(), getString(R.string.notify_no_network), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 创建房间
     * 房间号
     * 用户的权限
     * @param num
     * @param auth_bits
     */
    private void createRoom(int num, long auth_bits ) {
        if (Util.isNetworkAvailable(getActivity().getApplicationContext())) {
            if (num != 0) {
                int nums = num;
                if(mQavsdkControl != null && !mQavsdkControl.hasAVContext()){
                    startContext();
                }
                mQavsdkControl.enterRoom(nums, auth_bits);
                Toast.makeText(getActivity(), "正在进入直播中...", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getActivity(), getString(R.string.notify_no_network), Toast.LENGTH_SHORT).show();
        }
    }

    private int mLoginErrorCode =  AVError.AV_OK;
    private void startContext() {
        if (!mQavsdkControl.hasAVContext()) {

//            String phone = mSelfUserInfo.getUserPhone();
//            //if (mSelfUserInfo.getLoginType() == Util.TRUSTEESHIP)
//            phone = "86-" + phone;
//            Log.e(TAG, "import phone: " + phone+ "Usersig "+ mSelfUserInfo.getUsersig());
//
//
//            mLoginErrorCode = mQavsdkControl.startContext(
//                    phone, mSelfUserInfo.getUsersig());
            mLoginErrorCode = mQavsdkControl.startContext(
                    PreferencesStorageUtil.getUserId(getActivity()), PreferencesStorageUtil.getTsig(getActivity()));
            Log.e(TAG, "startContext mLoginErrorCode   " +mLoginErrorCode);
            if (mLoginErrorCode !=  AVError.AV_OK) {
                Log.e(TAG, "startContext mLoginErrorCode   " + mLoginErrorCode);
            }
        }
    }

//    //有吗
//    private void enterRoom() {
//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                JSONObject object = new JSONObject();
//                try {
//                    object.put(Util.EXTRA_ROOM_NUM, mChoseLiveVideoInfo.getProgrammId());
//                    object.put(Util.EXTRA_USER_PHONE, mSelfUserInfo.getUserPhone());
//                    System.out.println(object.toString());
//                    List<NameValuePair> list = new ArrayList<NameValuePair>();
//                    list.add(new BasicNameValuePair("viewerdata", object.toString()));
//                    String ret = HttpUtil.PostUrl(HttpUtil.enterRoomUrl, list);
//                    Log.d(TAG, "enter room" + ret);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
//    }



//    public Handler mHandler = new Handler(new Handler.Callback() {
//        @Override
//        public boolean handleMessage(android.os.Message msg) {
//            switch (msg.what) {
//                case REFRESH_COMPLETE:
//                    getLiveVideoInfo();
//                    mLiveAdapter.notifyDataSetChanged();
//                    mSwipeRefreshLayout.setRefreshing(false);
//                    break;
//                case REFRESH_ING:
//                    mLiveList.addAll((Collection<? extends LiveVideoInfo>) msg.obj);
//                    mLiveAdapter.refreshData(mLiveList);
////                    setLiveHeadImage();
//                    break;
//                case UPDATE_LIVE_TIMER_TASK:
//                    getLiveVideoInfo();
//                    break;
//                case UPDATE_USER_LOGO:
//                    mLiveAdapter.notifyDataSetChanged();
//                    break;
//                default:
//                    break;
//            }
//            return false;
//        }
//    });

//    public void setLiveHeadImage() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                boolean isChange = false;
//                ImageUtil tool = new ImageUtil();
//                for (int i = 0; i < mLiveList.size(); ++i) {
//                    if (mLiveList.get(i).getUserHeadImage() == null) {
//                        String param = "?imagepath=" + mLiveList.get(i).getHeadImagePath() + "&width=0&height=0";
//                        Bitmap headBitmap = tool.getImageFromServer(param);
//                        mLiveList.get(i).setUserHeadImage(headBitmap);
//                        isChange = true;
//                    }
//                }
//                if (isChange) {
//                    mHandler.sendEmptyMessage(UPDATE_USER_LOGO);
//                }
//            }
//        }).start();
//    }
//
//    protected void getLiveVideoInfo() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String response = HttpUtil.PostUrl(HttpUtil.getLiveListUrl, new ArrayList<NameValuePair>());
//                if (HttpUtil.FAIL == response.length()) {
//                    return;
//                }
//                if(!response.endsWith("}")){
//                    return;
//                }
//
//                JSONTokener jsonTokener = new JSONTokener(response);
//                try {
//                    JSONObject object = (JSONObject) jsonTokener.nextValue();
//                    int ret = object.getInt(Util.JSON_KEY_CODE);
//                    if (ret != HttpUtil.SUCCESS) {
//                        return;
//                    }
//
//                    JSONArray array = object.getJSONArray(Util.JSON_KEY_DATA);
//                    Message message = new Message();
//                    List<LiveVideoInfo> tmplist = new ArrayList<LiveVideoInfo>();
//                    for (int i = 0; i < array.length(); i++) {
//                        JSONObject jobject = array.getJSONObject(i);
//
//                        LiveVideoInfo item = new LiveVideoInfo(jobject.getInt(Util.EXTRA_PROGRAM_ID),
//                                jobject.getString(Util.EXTRA_SUBJECT), R.drawable.user,
//                                jobject.getInt(Util.EXTRA_VIEWER_NUM), jobject.getInt(Util.EXTRA_PRAISE_NUM),
//                                new UserInfo(jobject.getString(Util.EXTRA_USER_PHONE),
//                                        jobject.getString(Util.EXTRA_USER_NAME),
//                                        jobject.getString("headimagepath")),
//                                jobject.getString(Util.EXTRA_GROUP_ID), "12345");
//                        item.setCoverpath(jobject.getString("coverimagepath"));
//                        tmplist.add(item);
//                    }
//                    message.what = REFRESH_ING;
//                    message.obj = tmplist;
//                    mHandler.sendMessage(message);
////                        }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }

}
